from django.http import HttpResponse
import json, hashlib, hmac, urllib, time, string, random
from setting import CONSUMER_KEY, CONSUMER_SECRET
from models import *

def _try_del(d, k):
    try:
        del d[k]
    except:
        pass

def _random_str(length, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for x in range(length))
    
def _get_oauth_token_secret(oauth_token):
    try:
        ut = UserToken.objects.get(oauth_token=oauth_token)
        return ut.oauth_token_secret
    except UserToken.DoesNotExist:
        pass
    except Exception, e:
        print e
    return ''

def _set_oauth_token_secret(oauth_token, oauth_token_secret):
    try:
        ut = UserToken.objects.get(oauth_token=oauth_token)
        ut.oauth_token_secret = oauth_token_secret
        ut.save()
    except UserToken.DoesNotExist:
        try:
            ut = UserToken(oauth_token=oauth_token, oauth_token_secret=oauth_token_secret)
            ut.save()
        except Exception, e:
            print e
    except Exception, e:
        print e

def _urlencode(s, safe=''):
    return urllib.quote(s.encode('UTF-8'), safe)

def _make_oauth_signature(http_method='GET', base_uri='', parameters={}, oauth_token_secret=''):
    param = []
    for k in parameters.keys():
        v = parameters[k]
        param.append("%s=%s" % (_urlencode(k), _urlencode(v)))
    param.sort()
    base_string = "%s&%s&%s" % (http_method, _urlencode(base_uri), _urlencode("&".join(param)))
    key = CONSUMER_SECRET + '&' + oauth_token_secret
    oauth_signature = hmac.new(key, base_string, hashlib.sha1).digest().encode('base64').rstrip()
    return oauth_signature

def _make_url(base_uri='', parameters={}):
    return base_uri + '?' + urllib.urlencode(parameters)

def _read_url(url):
    try:
        f = urllib.urlopen(url)
        return f.read()
    except Exception, e:
        print e
    return ''

def _field(request):
    if 'GET' == request.method:
        return request.GET
    elif 'POST' == request.method:
        return request.POST
    return None

def _resp_json(d=None):
    return HttpResponse(json.dumps(d), mimetype="application/json")

def _request_access_token(oauth_token, oauth_token_secret, oauth_verifier=None):
    param = {'oauth_consumer_key' : CONSUMER_KEY,
            'oauth_signature_method' : 'HMAC-SHA1',
            'oauth_timestamp' : str(int(time.time())),
            'oauth_nonce' : _random_str(31),
            'oauth_version' : '1.0',
            'oauth_token' : oauth_token}
    if oauth_verifier is not None:
        param['oauth_verifier'] = oauth_verifier
    base_uri = "https://openapi.kuaipan.cn/open/accessToken"
    param['oauth_signature'] = _make_oauth_signature(base_uri=base_uri, parameters=param, oauth_token_secret=oauth_token_secret)
    url = _make_url(base_uri, param)
    return _read_url(url)

def get_access_token(request):
    f = _field(request)
    oauth_token = str(f.get('oauth_token', ''))
    oauth_token_secret = str(f.get('oauth_token_secret', ''))
    oauth_verifier = str(f.get('oauth_verifier', ''))
    r = _request_access_token(oauth_token, oauth_token_secret, oauth_verifier)
    try:
        resp = json.loads(r)
    except Exception, e:
        print e, r
        return _resp_json(None)
    _set_oauth_token_secret(resp.get('oauth_token'), resp.get('oauth_token_secret'))
    _try_del(resp, 'oauth_token_secret')
    return _resp_json(resp)

def get_oauth_signature(request):
    f = _field(request)
    http_method = str(f.get('http_method', 'GET'))
    base_uri = f.get('base_uri', '')
    base_uri = _urlencode(base_uri, ':/')
    oauth_token_secret = str(_get_oauth_token_secret(f.get('oauth_token', '')))
    parameters = f.copy()
    _try_del(parameters, 'http_method')
    _try_del(parameters, 'base_uri')
    _try_del(parameters, 'oauth_signature')
    _try_del(parameters, 'oauth_token_secret')
    oauth_signature = _make_oauth_signature(http_method, base_uri, parameters, oauth_token_secret)
    print oauth_signature
    return _resp_json({'oauth_signature' : oauth_signature})
  
def callback(request):
    f = _field(request)
    return _resp_json(f)

def test(request):
    print request.POST
    print request.GET
    print request.FILES
    return HttpResponse('')

